package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.ParseState;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;

public class CyolNewsAnalyse implements AnalyseNews {

//http://zqb.cyol.com/html/2014-02/10/nw.D110000zgqnb_20140210_1-03.htm
	private static final String[] regex={
		"http://.*.cyol.com/content/[0-9]*-[0-9]*/[0-9]*/content_[0-9]*.htm",
		"http://.*.cyol.com/html/[0-9]*-[0-9]*/[0-9]*/.*.htm"
	};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		String htmltxt=urlMeta.getHtml();
		Document doc=Jsoup.parse(htmltxt);
		NewsMeta news=new NewsMeta();
		if("本网页已删除".equals(doc.select("title").text())){
			news.setUpdateUrl(ParseState.ERR404.toString());
			return news;
		}

		String title=doc.select(".bttitle").text();
		Long date=DateUtils.matchDate(doc.select(".laiy").text());

		if(date==null){
			date=DateUtils.matchDate(url);
		}
		String content=HtmlCleaner.getContentHtml(url, doc.select("div.zhengwen"));
			if(StringUtils.isBlank(content)){
				content=HtmlCleaner.getContentHtml(url, doc.select("div.zw"));
			}
		news.setUrl(url);
		news.setTitle(title);
		news.setDate(date);
		news.setContent(content);
		/*
		 * 作者
		 */
		String authorStr=null;
		authorStr=doc.select("div.lai").text();
		if(StringUtils.isBlank(authorStr)){
			authorStr=doc.select("h6.laiy p").text();
		}
		String author=StringUtils.substringBetween(authorStr, "《","》");
		if(StringUtils.isBlank(author)){
			author=StringUtils.substringBetween(authorStr, "来源："," ");
			if(StringUtils.isBlank(author)){
				author=StringUtils.substringAfter(authorStr, "来源：");
			}
		}

		news.setAuthor(author);
		return news;
	}

	public static void main(String[] args) {
		String url="http://news.cyol.com/content/2014-05/07/content_10054368.htm";
		CyolNewsAnalyse test=new CyolNewsAnalyse();
		System.out.println(test.isDetailPage(url));
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		System.out.println(DoMainUtils.GetDomainName(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
